package com.example.ruiji.controller.login;

import com.example.ruiji.dao.mapper.UserMapper;
import com.example.ruiji.pojo.User;
import com.example.ruiji.service.userSerice.UserServiceImpl;
import com.example.ruiji.utils.token.MyTokenUtils;
import com.example.ruiji.utils.vo.LoginResult;
import com.example.ruiji.utils.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:BaiYiChen
 * Date:2022/5/2 18:08
 *
 * @author BaiYiChen
 */
@RestController
public class LoginRestController {
@Autowired
private UserMapper userMapper;
  @Autowired
  private UserServiceImpl userService;
  
  @RequestMapping("/login.do")
  public Map login(@RequestParam Map map, HttpServletResponse resp) throws IOException {
    String username = map.get("username").toString();
    String password = map.get("password").toString();
    /**设置响应头允许ajax跨域访问**/
    resp.setHeader("Access-Control-Allow-Origin","*");
    /*星号表示所有的异域请求都可以接受，*/
    resp.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
    User user = userService.findUserByAccount(username);
    HashMap<String, String> hashMap=null;
    
    if (user!=null&&user.getPassword().equals(password)){
      MyTokenUtils.user=user;
      String salt = user.getSalt();
      String accessToken = MyTokenUtils.createToken(username, salt);
      System.out.println(accessToken);
      
      hashMap = new HashMap<>();
      hashMap.put("access_token", accessToken);
      hashMap.put("username", username);
      resp.addCookie(new Cookie("access_token",accessToken));
      return LoginResult.login(0,"登录成功", hashMap);
    }
    
    return LoginResult.login(1,"登录失败", null);
  }
}
